angular.module('imsApp').controller('advDataStatisticsController', ['$scope', '$state', 'AdvDataStatisticsManager', '$uibModal','$filter', function ($scope, $state, AdvDataStatisticsManager, $uibModal,$filter) {

    $scope.search = {
        pageNo: $state.params.pageNo || 1,
        pageSize: $state.params.pageSize || 10,
        adStyle: $state.params.adStyle || 0,
        campaignId: $state.params.campaignId || 0,
        startDay: $state.params.startDay || moment().startOf('day').add(-109, 'days').format("YYYY-MM-DD"),
        endDay: $state.params.endDay || moment().endOf('day').add(0, 'days').format("YYYY-MM-DD")
    };

    //Choose date
    $scope.rangeDate = {
        startDate: moment($scope.search.startDay).format('X'),
        endDate: moment($scope.search.endDay).format('X'),
        onSelected: function (data, scope) {  //submit
            $scope.search.startDay = moment(new Date(parseFloat(data.startDate) * 1000)).format("YYYY-MM-DD");
            $scope.search.endDay = moment(new Date(new Date(parseFloat(data.endDate) * 1000))).format("YYYY-MM-DD");
            $state.go($state.current.name, $scope.search)

        }
    };

    $scope.campaignChange = function (campaign) {
        $scope.search.campaignId = campaign
        $scope.search.pageNo=1;
        $scope.search.pageSize=10;
        $state.go($state.current.name, $scope.search)

    }

    $scope.typeChange=function (adStyle) {
        $scope.search.adStyle = adStyle
        $scope.search.pageNo=1;
        $scope.search.pageSize=10;
        $state.go($state.current.name, $scope.search)
    }


    $scope.paginationConf = {
        currentPage: $state.params.pageNo || 1,
        itemsPerPage: $state.params.pageSize || 10,
        pagesLength: 9,
        search: 0,
        onChange: function () {
            $scope.search.pageNo = this.currentPage;
            $scope.search.pageSize = this.itemsPerPage;
            $state.go($state.current.name, $scope.search)

        }
    };

    AdvDataStatisticsManager.advDataList([$scope.search.pageNo, $scope.search.pageSize], $scope.search).then(function (result) {
        $scope.lists = result.data.pageList;
        $scope.countStat=result.data.countStat;
        $scope.paginationConf.totalItems = result.data.total;
    })

    AdvDataStatisticsManager.advCampaignsList().then(function (result) {
        console.log(result);
        $scope.advCampaigns = result.data.pageList;
        $scope.campaign=$filter('filter')( $scope.advCampaigns,{id:$scope.search.campaignId})
    })
    //导出excel

    function getExplorer() {
        var explorer = window.navigator.userAgent;
        //ie
        if (explorer.indexOf("MSIE") >= 0) {
            return 'ie';
        }
        //firefox
        else if (explorer.indexOf("Firefox") >= 0) {
            return 'Firefox';
        }
        //Chrome
        else if (explorer.indexOf("Chrome") >= 0) {
            return 'Chrome';
        }
        //Opera
        else if (explorer.indexOf("Opera") >= 0) {
            return 'Opera';
        }
        //Safari
        else if (explorer.indexOf("Safari") >= 0) {
            return 'Safari';
        } else {
            return 'unknown';
        }
    }
    $scope.method1 =function(tableid) {//整个表格拷贝到EXCEL中
        if (getExplorer() == 'ie' || getExplorer() == "unknown") {
            this.getXlsFromTbl('targetTable', null);
        } else {
            tableToExcel(tableid)
        }
    }
    var tableToExcel = (function() {
        var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>', base64 = function(
            s) {
            return window.btoa(unescape(encodeURIComponent(s)))
        }, format = function(s, c) {
            return s.replace(/{(\w+)}/g, function(m, p) {
                return c[p];
            })
        }
        return function(table, name) {
            if (!table.nodeType)
                table = document.getElementById(table)
            var ctx = {
                worksheet : name || 'Worksheet',
                table : table.innerHTML
            }
            var excelData = uri + base64(format(template, ctx));
            var downNode = document.getElementById('download');
            downNode.setAttribute("href",excelData);
            downNode.setAttribute("download",getExcelFileName());
        }
    })()

    /*----------------------------------*/

    function getXlsFromTbl(inTblId, inWindow) {

        try {

            var allStr = "";

            var curStr = "";

            if (inTblId != null && inTblId != "" && inTblId != "null") {

                curStr = getTblData(inTblId, inWindow);

            }

            if (curStr != null) {

                allStr += curStr;

            } else {

                alert("你要导出的表不存在！");

                return;

            }

            var fileName = getExcelFileName();

            doFileExport(fileName, allStr);

        } catch (e) {

            alert("导出发生异常:" + e.name + "->" + e.description + "!");

        }

    }

    function getTblData(inTbl, inWindow) {

        var rows = 0;

        var tblDocument = document;

        if (!!inWindow && inWindow != "") {

            if (!document.all(inWindow)) {

                return null;

            } else {

                tblDocument = eval(inWindow).document;

            }

        }

        var curTbl = tblDocument.getElementById(inTbl);

        var outStr = "";

        if (curTbl != null) {

            for (var j = 0; j < curTbl.rows.length; j++) {

                for (var i = 0; i < curTbl.rows[j].cells.length; i++) {

                    if (i == 0 && rows > 0) {

                        outStr += " /t";

                        rows -= 1;

                    }

                    outStr += curTbl.rows[j].cells[i].innerText + "/t";

                    if (curTbl.rows[j].cells[i].colSpan > 1) {

                        for (var k = 0; k < curTbl.rows[j].cells[i].colSpan - 1; k++) {

                            outStr += " /t";

                        }

                    }

                    if (i == 0) {

                        if (rows == 0
                            && curTbl.rows[j].cells[i].rowSpan > 1) {

                            rows = curTbl.rows[j].cells[i].rowSpan - 1;

                        }

                    }

                }

                outStr += "/r/n";

            }

        }

        else {

            outStr = null;

            alert(inTbl + "不存在!");

        }

        return outStr;

    }

    function getExcelFileName() {

        var d = new Date();

        var curYear = d.getFullYear();

        var curMonth = "" + (d.getMonth() + 1);

        var curDate = "" + d.getDate();

        var curHour = "" + d.getHours();

        var curMinute = "" + d.getMinutes();

        var curSecond = "" + d.getSeconds();

        if (curMonth.length == 1) {

            curMonth = "0" + curMonth;

        }

        if (curDate.length == 1) {

            curDate = "0" + curDate;

        }

        if (curHour.length == 1) {

            curHour = "0" + curHour;

        }

        if (curMinute.length == 1) {

            curMinute = "0" + curMinute;

        }

        if (curSecond.length == 1) {

            curSecond = "0" + curSecond;

        }

        var fileName = "数据统计" + "_" + curYear + curMonth + curDate + "_"

            + curHour + curMinute + curSecond + ".xls";

        return fileName;

    }



}])

